package com.mrtan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.mrtan.bean.Account;
import com.mrtan.bean.AccountRoleMapping;
import com.mrtan.mapper.AccountMapper;
import com.mrtan.mapper.AccountRoleMappingMapper;
import com.mrtan.service.AccountService;
import com.mrtan.vo.AccountInsertVO;
import com.mrtan.vo.AccountWhereVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

// service 目前和 component一样，但是为了区分。还是使用Service.因为后期不保证会对Service进行定制化扩展
@Service  //交给spring容器管理，相当于<bean id="accountServiceImpl" class="com.hm.service.impl.AccountServiceImpl"/>
public class AccountServiceImpl implements AccountService {
    @Resource
    private AccountMapper accountMapper;
    @Resource
    private AccountRoleMappingMapper accountRoleMappingMapper;
    @Override
    public List<Account> findAll(AccountWhereVO where) {
        return accountMapper.selectAll(where);
    }

    @Override
    public Account findById(Integer id) {
        return accountMapper.selectByPrimaryKey(id);
    }

    @Override
    public Account findByUsernameAndPassword(String username, String password) {
        Account account = accountMapper.selectByUsernameAndPassword(username, password);
        System.out.println(account);
        account.setPassword(null);
        return account;
    }

    @Override
    public void add(AccountInsertVO account) {
        // 将 AccountInsertVO中的属性复制到 Account类型中
        Account account1 = BeanUtil.copyProperties(account, Account.class);
        accountMapper.insertSelective(account1);
    }

    @Override
    @Transactional // 开启事务
    public void associationRole(int accountId, Integer[] roleIds) {
        //先删除之前的关联
        accountRoleMappingMapper.delByAccountId(accountId);
        //再添加新的关联
        accountRoleMappingMapper.insertBatch(accountId,roleIds);
    }
}
